package domain.entities;

import org.hibernate.LockMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: nico
 * Date: 22/10/12
 * Time: 12:57
 * To change this template use File | Settings | File Templates.
 */
public class RemoteAccessDAO extends HibernateDaoSupport{
    private static final Logger log = LoggerFactory.getLogger(RegionsDAO.class);

    public void save(RemoteAccess transientInstance) {
        log.debug("saving RemoteAccess instance");
        try {
            getHibernateTemplate().save(transientInstance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }

    public RemoteAccess findById(String hash) {
        log.debug("getting RemoteAccess instance with hash: " + hash);
        try {
            RemoteAccess instance = (RemoteAccess) getHibernateTemplate().get("RemoteAccess",
                    hash);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

    public List findAll() {
        log.debug("finding all Remote Access instances");
        try {
            String queryString = "from RemoteAccess ";
            return getHibernateTemplate().find(queryString);
        } catch (RuntimeException re) {
            log.error("find all failed", re);
            throw re;
        }
    }

    public RemoteAccess merge(RemoteAccess detachedInstance) {
        log.debug("merging RemoteAccess instance");
        try {
            RemoteAccess result = (RemoteAccess) getHibernateTemplate().merge(
                    detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public void attachDirty(RemoteAccess instance) {
        log.debug("attaching dirty RemoteAccess instance");
        try {
            getHibernateTemplate().saveOrUpdate(instance);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

    public void attachClean(RemoteAccess instance) {
        log.debug("attaching clean RemoteAccess instance");
        try {
            getHibernateTemplate().lock(instance, LockMode.NONE);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

    public static RemoteAccessDAO getFromApplicationContext(ApplicationContext ctx) {
        return (RemoteAccessDAO) ctx.getBean("RemoteAccessDAO");
    }

}
